<template>
  <j-modal
    switchFullscreen
    :title="title"
    :width="500"
    :ok=false
    :visible="visible"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="组织编号"
          :hidden="false"
        >
          <a-input id="orgCode" placeholder="请输入组织编号" v-decorator="['orgCode', validatorRules.orgCode ]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="组织名称"
          :hidden="false"
        >
          <a-input id="orgName" placeholder="请输入组织名称" v-decorator="['orgName', validatorRules.orgName ]"/>
        </a-form-item>
        <a-form-item v-if="(model.orgType !== '1') || (form.getFieldValue('orgType') == '2') " :labelCol="labelCol"
                     :wrapperCol="wrapperCol" :hidden="seen"
                     label="上级组织">
          <a-tree-select
            style="width:100%"
            :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
            :treeData="departTree"
            v-decorator="['parentCode']"
            placeholder="请选择上级组织"
            :replaceFields="{children:'children', title:'orgName',value:'orgCode'}"
            :disabled="condition">
          </a-tree-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="组织类型">
          <cn-dict-select-tag
            :options="{ value: 'dictDataCode', label: 'dictDataDesc' }"
            :triggerChange="true"
            dictCode="org_type"
            v-decorator="['orgType', validatorRules.orgType]"
            placeholder="请选择组织类型"
            @change="handleSelectTag"
          />
        </a-form-item>
<!--        <a-form-item-->
<!--          :labelCol="labelCol"-->
<!--          :wrapperCol="wrapperCol"-->
<!--          label="SAP组织编号"-->
<!--          :hidden="false"-->
<!--        >-->
<!--          <a-input id="orgCode" placeholder="请输入SAP组织编号" v-decorator="['sapOrgCode' ]"/>-->
<!--        </a-form-item>-->
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="选择职位">
          <!--                    <a-input placeholder="请输入部门负责人名称" v-decorator="['leaderName', {}]"/>-->
          <j-select-user :multiple="false"
                         v-decorator="['leaderName']"
                         :giveBackList="model.custList"
                         selectButtonText="选择"
                         :inputs="true"
                         searchIcon="search"
                         :returnName="true"
                         :disabled="disableSubmit"
                         @select="handleLeaderName">
          </j-select-user>
          <a-input type="hidden" placeholder="负责人编号" v-decorator="['leaderCode']"/>
        </a-form-item>

        <!--                <a-form-item-->
        <!--                        :labelCol="labelCol"-->
        <!--                        :wrapperCol="wrapperCol"-->
        <!--                        label="地址">-->
        <!--                    <a-input placeholder="请输入地址" v-decorator="['address', {}]"/>-->
        <!--                </a-form-item>-->
        <!--                <a-form-item-->
        <!--                        :labelCol="labelCol"-->
        <!--                        :wrapperCol="wrapperCol"-->
        <!--                        label="排序">-->
        <!--                    <a-input-number v-decorator="[ 'departOrder',{'initialValue':0}]"/>-->
        <!--                </a-form-item>-->
        <!--                <a-form-item-->
        <!--                        :labelCol="labelCol"-->
        <!--                        :wrapperCol="wrapperCol"-->
        <!--                        label="备注">-->
        <!--                    <a-textarea placeholder="请输入备注" v-decorator="['memo', {}]"/>-->
        <!--                </a-form-item>-->

      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import { httpAction } from '@/api/manage'
import { queryDepartTreeList, queryIdTree } from '@/api/api'
import { pick } from 'lodash'
import ATextarea from 'ant-design-vue/es/input/TextArea'
import JSelectUser from '@comp/cn-select-popup/JSelectUser'

export default {
  name: 'SysDepartModal',
  components: { ATextarea, JSelectUser },
  data() {
    return {
      departTree: [],
      orgTypeData: [],
      phoneWarning: '',
      orgName: '',
      orgCode: '',
      title: '操作',
      isAll: false,
      seen: false,
      visible: false,
      condition: false,
      disableSubmit: false,
      model: {},
      menuhidden: false,
      menuusing: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },

      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        orgName: { rules: [{ required: true, message: '' }] },
        orgCode: { rules: [{ required: true, message: '' }] },
        orgType: { rules: [{ required: true, message: '' }] }
        // mobile: {rules: [{validator: this.validateMobile}]}
      },
      url: {
        add: '/cnOrgController/saveOrUpdateEntity'
      },
      dictDisabled: true
    }
  },
  created() {
    this.loadTreeData(0)
  },
  methods: {
    initDictConfig() {

    },
    loadTreeData(orgCode) {
      var that = this
      // if (this.isAll) {
        queryDepartTreeList().then((res) => {
          if (res.success) {
            that.departTree = []
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i]
              temp.key = temp.orgCode
              this.departTree.push(temp)
            }
          }
        })
      // } else {
      //   queryIdTree({ orgCode }).then((res) => {
      //     if (res.success) {
      //       that.departTree = []
      //       let temp = res.result
      //       temp.key = temp.orgCode
      //       that.departTree.push(temp)
      //     }
      //
      //   })
      // }
    },
    handleSelectTag(value) {
      if (value == 1) {
        this.seen = true
      } else {
        this.seen = false
      }
    },

    add(depart) {
      if (depart) {
        this.isAll = true
        this.seen = false
        this.dictDisabled = false
      } else {
        this.isAll = true
        this.seen = true
        this.dictDisabled = true
      }
      this.edit(depart)
    },
    addnew(depart) {
      this.isAll = true
      if (depart.orgCode) {
        this.seen = false
        this.dictDisabled = false
      } else {
        this.seen = true
        this.dictDisabled = true
      }
      this.form.resetFields()
      this.model = Object.assign({}, depart)
      if(depart.leaderCode){
        this.model.custList =[{
          userName:depart.leaderCode,
          realName:depart.leaderName,
        }]
      }
      this.visible = true
      this.model.parentCode = depart.parentCode
      if (this.model.parentCode) this.loadTreeData(this.model.parentCode)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'orgType', 'orgName', 'orgNameEn', 'orgNameAbbr', 'departOrder', 'description', 'parentCode', 'sapOrgCode','orgType', 'orgCode','leaderName', 'mobile', 'fax', 'address', 'memo', 'status', 'delFlag'))
      })
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, {})
      this.visible = true
      this.model.parentCode = record != null ? record.toString() : null


      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'orgType', 'orgName', 'orgNameEn', 'orgNameAbbr', 'departOrder', 'description', 'parentCode', 'sapOrgCode', 'orgType', 'orgCode', 'mobile', 'fax', 'address', 'memo', 'status', 'delFlag'))
      })
    },
    close() {
      this.$emit('close')
      this.disableSubmit = false
      this.visible = false
    },

    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          //时间格式化
          console.log(formData)
          httpAction(this.url.add, formData, 'post').then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              if (this.model.parentCode) this.loadTreeData(this.model.parentCode)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false

          })

        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateMobile(rule, value, callback) {
      if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
        callback()
      } else {
        callback('您的手机号码格式不正确!')
      }
    },
    // 用户选择
    handleLeaderName(list) {
      // this.model.leaderCode = list.userName
      console.log(list)
      if(list.length){
        this.form.setFieldsValue({ leaderCode: list[0].userName })
      }else {
        this.form.setFieldsValue({ leaderCode: '' })
      }


    }
  }
}
</script>

<style scoped>

</style>
